# -*- coding: utf-8 -*-
"""
Create Time: 2019/11/14 15:02
Author: yxl
Descript:
"""
import json

from django.shortcuts import redirect
from django.urls import reverse
from django_redis import get_redis_connection
from index.models import MXUser


def cookie_to_redis(request, response):
    # 1,获取cookie
    cookie_data = request.COOKIES.get('cookie_data')

    # 如果cookie中有值
    if cookie_data:

        cookie_data = json.loads(cookie_data)

        redis_cli = get_redis_connection('cart')

        username = request.session.get('username')
        user = MXUser.objects.get(username=username)

        redis_data = redis_cli.get('redis_data_%d' % user.id)
        # 2，如果redis里面没有值
        if not redis_data:
            # 3,cookie的数据直接赋值给redis
            redis_data = cookie_data
        else:

            redis_data = json.loads(redis_data.decode())
            # 如果redis中有数据
            for i in cookie_data:
                redis_data[i] = cookie_data[i]

        # 清除cookie中的数据
        response.delete_cookie('cookie_data')

        # 设置redis
        redis_data = json.dumps(redis_data)
        redis_cli.set('redis_data_%d' % user.id, redis_data)


    return response

# 判断用户有没有登陆的装饰器
def is_login(func):
    def inner(request, *args, **kwargs):
        if not request.session.get('username'):
            return redirect(reverse('index:login'))
        return func(request, *args, **kwargs)
    return inner